package com.hundsun.cprs.yyt.service.match.core.command;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MatchingCommandQueue {

    private static final Log logger = LogFactory.getLog(MatchingCommandQueue.class);

    private final Lock lock = new ReentrantLock();
    private final Condition empty = lock.newCondition();

    private Queue<MatchingCommand> commands = new LinkedList<MatchingCommand>();
    private int commandsCount = 0;
    private AtomicBoolean working = new AtomicBoolean(true);

    public void addCommand(MatchingCommand command) {
        if (command == null) {
            if (logger.isErrorEnabled()) {
                logger.error("null command recived!");
            }
            return;
        }
        lock.lock();
        try {
            commands.offer(command);
            commandsCount++;
            if (working.get() && commandsCount >= 1) {// 指令执行线程有事干了
                empty.signal();
            }
        } finally {
            lock.unlock();
        }
    }

    public MatchingCommand getCommand() throws InterruptedException {
        lock.lock();
        try {
            while (!working.get() || commandsCount == 0) {
                empty.await();
            }
            commandsCount--;
            return commands.poll();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 得到指令队列大小
     * 
     * @return
     */
    public int getQueueSize() {
        lock.lock();
        try {
            return commandsCount;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 当前是否工作状态(可出可入)
     * 
     * @return
     */
    public boolean getWorking() {
        return this.working.get();
    }
}
